import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PrismaService } from "src/prisma.service";
import { jwtConstants } from "./constants";
import { User } from "@prisma/client";
import { TJwtPayload } from "./typing";
import { Injectable } from "@nestjs/common";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private prisma: PrismaService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromHeader('token'),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    })
  }
  async validate(payload: TJwtPayload) {
    const user: User = await this.prisma.user.findUnique({
      where: {userId: payload.userId, password: payload.password}
    });
    if(!user) {
      return false;
    }
    return { userId: payload.userId, password: payload.password, username: user.username };
  }
}
